﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using WChat;
using HuanQiuCrm.Properties;
using System.IO;
using Newtonsoft.Json.Linq;

namespace HuanQiuCrm {
    public partial class Form1 : Skin_DevExpress {
        //机器人回复
        Auto_Reply_EventHandler auto_reply = new Auto_Reply_EventHandler();
        LoginService ls = new LoginService();
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool FlashWindow(IntPtr handle, bool bInvert);
        SqlHandle sql = new SqlHandle();
        private  int msg_cunt = 0;
        private WinXinBox global_wxb;
        private string cl_direct;
        private  object click_login_result = null;
        //临时保存数据_me user
        public List<WXUser> pro_me = new List<WXUser>() { };
        public WXUser _me;
        public WXUser pro_user;
        private int zong = 15;
        public static Dictionary<string, WinXinBox> login_wxb = new Dictionary<string, WinXinBox>();
        public static Dictionary<string, Image> login_icon = new Dictionary<string, Image>();
        Settings st = new Settings();
        TabPage MyTabPage;
        string ChildName = string.Empty;
        private  List<Image> headIconLis = new List<Image>();

        public Form1() {
            InitializeComponent();
            sql.DeleteMyFriendsTab(st.UseAcct);   //清空微信好友表
            if (sql.HaveTheTab(st.UseAcct,"")) {
                sql.DeleteMyFriendsTab(st.UseAcct);   //如果没有清空，则再次清空
            }
            loginwx.Login += Loginwx_Login;
        }

        private void Loginwx_Login( Image lgrseult ) {
            main(lgrseult);
        }

        public void main(Image img) {
              string icon_path = path.paths + "\\login_icon.jpg";   //工作时的路径
              string lgresult = null;
                if (loginwx.login_result is string&& loginwx.login_result!=null) {
                if (img != null) {    //等图像不为空再进行操作，大部分挂掉的原因都是从这里
                    WinXinBox.num++;
                    lgresult = loginwx.login_result as string;
                    int mul = 0;
                    imageList1.Images.Add(img);   //向图像数组存入头像
                    headIconLis.Add(img);
                    if (File.Exists(icon_path)) {
                        File.Delete(icon_path);
                    }
                    img.Save(icon_path);
                    if (lgresult.Contains("https://web.wechat.com/")) {
                        mul = 3;
                    }
                    else if (lgresult.Contains("https://wx2.qq.com/")) {
                        mul = 2;
                    }
                    else if (lgresult.Contains("https://wx.qq.com/")) {
                        mul = 1;
                    }
                    WinXinBox wxb = new WinXinBox();
                    wxb.Setlogin_redirect(lgresult, mul, auto_reply, st.UseAcct, st.CanQuickReply);
                    wxb.Dock = DockStyle.Fill;
                    int page = wxTabContral1.TabCount;
                    wxb.UnReadMsg += Wxb_UnReadMsg;
                    wxb.Success_Login += Wxb_Success_Login;
                    wxb.NewAllMsg += Wxb_NewAllMsg;
                    wxb.Close += Wxb_Close;   //关闭选项卡的委托
                    MyTabPage = new TabPage();//创建TabPage对象  
                    MyTabPage.Controls.Add(wxb);
                    wxTabContral1.TabPages.Add(MyTabPage);
                    wxTabContral1.SelectedIndex = page;
                    loginwx.login_result = null;   //清空复位
                    global_wxb = wxb;
                    cl_direct = lgresult;
                 //  WXService.WriteLoginDirect(lgresult);
                    login_icon.Add(cl_direct, img);
                    this.BeginInvoke((Action)delegate () {
                        for (int i = 0; i < loginwx.headpic.Count; i++) {
                            if (loginwx.headpic[i] == img) {
                                MyTabPage.ImageIndex = i;
                            }
                        }
                        MyTabPage.Text = "登录中...";
                    });
                }
            }
        }
        /// <summary>
        /// 当掉线后移除相应选项卡
        /// </summary>
        /// <param name="close"></param>
        private void Wxb_Close( string close ) {
            this.BeginInvoke((Action)delegate () {
                this.wxTabContral1.TabPages.RemoveByKey(close);
                MessageBox.Show("当前账号:" + close + "，已退出登录！");
            });
           login_wxb.Remove(close);   //将该值移除,防止重复添加
        }

        private void Wxb_NewAllMsg(WXUser me, WXUser _user) {
            _me = me;
            if (_me.NickName != string.Empty) {
                pro_me.Add(_me);
            }
            pro_user = _user;
        }
        //事件委托  改变选项卡的Name和Text
        private void Wxb_Success_Login(string name) {
            this.BeginInvoke((Action)delegate () {
                MyTabPage.Name = name;
                ChildName = name;
                string text = name.Length > 4 ? name.Substring(0, 4)+"..": name;
                MyTabPage.Text = text;
                login_wxb.Add(name, global_wxb);
                WXService.WriteLoginDirect("MyNick", name);
            });
        }
        //呼吸效果  调用控件方法
        private void Wxb_UnReadMsg(string pageName,string msg) {
            msg_cunt = msg_cunt + 1;
            this.BeginInvoke((Action)delegate () {
                if (wxTabContral1.TabPages != null) {
                    wxTabContral1.TipTextAdd(pageName,"1");
                    FlashWindow(this.Handle, true);     //闪烁任务栏
                    show_msg.ShowBalloonTip(5000, pageName, msg, ToolTipIcon.Info);  //显示气泡消息
                }
            });
        }

        public static string ReadLogin(string path) {
            FileStream fs = new FileStream(path, FileMode.Open);
            StreamReader se = new StreamReader(fs);
            string s = se.ReadToEnd();
            se.Close();
            return s;
        }
   
        //设置按钮
        private void skinButton2_Click(object sender, EventArgs e) {
                SttingForm sf = new SttingForm();
                sf.Show();
        }

        //新增客服权限判断
        private void skinButton1_Click_1(object sender, EventArgs e) {
            if (WinXinBox.num == zong)
            {
                MessageBox.Show("登陆账号已达到上限，请联系管理员！！");
                return;
            }
            if (st.CanAddWx == 0) {
                MessageBox.Show("抱歉，您没有登录微信权限，请联系管理员！");
            }
            else {
                try
                {
                    loginwx lx = new loginwx();
                    lx.Show();
                }
                catch
                {
                    MessageBox.Show("遇到未知错误,请重启软件！");
                }
            }
        }
   
        private void robot_reply_Click(object sender, EventArgs e) {
            if (st.CanRob == 0) {
                MessageBox.Show("抱歉。您没有获得此权限，请联系管理员！");
            }
            else {
                robot na = new robot();
                na.Show();
                na.RobotReply += Na_RobotReply;
                na.AotumaticReply += Na_AotumaticReply;
            }
        }
        //图灵机器人
        private void Na_RobotReply(bool asd,List<string> arr) {
            if (asd == true) {
                auto_reply.Open_Close(true,arr);
            }
            else {
                auto_reply.Open_Close(false,arr);
            }
        }
        //智能回复
        private void Na_AotumaticReply( bool asd, List<string> arr ) {
            if (asd == true) {
                auto_reply.Aotu_reply(true, arr);
            }
            else {
                auto_reply.Aotu_reply(false, arr);
            }
        }
        //群发助手判断权限是否使用
        private void tbn_AllSend_Click(object sender, EventArgs e) {
            if (st.CanMass == 0) {
                MessageBox.Show("抱歉，您不能使用此功能，请联系管理员！");
            }
            else {
                AllSend_Form AF = new AllSend_Form();
                AF.Get_Name(pro_me, pro_user);
                AF.Show();
            }

        }

        //注销按钮事件
        private void write_off_Click(object sender, EventArgs e) {
            Settings st = new Settings();
            st.UseAcct = null;
            st.UsePas = null;
            st.Save();

            //DAL.LoginStatusService ls = new DAL.LoginStatusService();
            //if (st.UseAcct!="") {
            //    ls.SetStatusLand(ls.SearchAdministration(st.UseAcct), st.UseAcct, 0);     //设置退出状态
            //    ls.SetLoginChild(st.UseAcct, string.Empty, 0);
            //}
            this.Close();
        }

        #region 杂项

        private void btn_message_manege_Click(object sender, EventArgs e) {
            if (st.CanLooChaLog == 0) {
                MessageBox.Show("抱歉。您没有获得查看权限，请联系管理员！");
            }
            else {
                Mess_Manage mm = new Mess_Manage();
                mm.Show();
            }
        }

        private void btn_about_Click(object sender, EventArgs e) {
            About ab = new About();
            ab.Show();
        }

        private void btn_costum_analysls_Click(object sender, EventArgs e) {
            costum_analy ca = new costum_analy();
            ca.Show();
        }

        private void btn_Consult_Click(object sender, EventArgs e) {
            SensitiveMenage sm = new SensitiveMenage();
            sm.Show();
        }

        private void btn_statistic_anal_Click(object sender, EventArgs e) {
            Customer cm = new Customer(ChildName);
            cm.Show();
        }

        #endregion

        #region 打开IE安装文件
        string ieSetuppath = System.Environment.CurrentDirectory + "\\";

        private void OpenSetupExe( string path ) {
            try {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(path);
                info.WorkingDirectory = System.IO.Path.GetDirectoryName(path);
                System.Diagnostics.Process.Start(info);
            }
            catch (Exception) {

            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e) {
          
            Settings st = new Settings();
            if (Convert.ToInt32(new WebBrowser().Version.ToString().Substring(0, new WebBrowser().Version.ToString().IndexOf("."))) < 9) {
                if (System.Environment.Is64BitOperatingSystem) {
                    string x64 = "IE9-Windows7-x64-chs.exe";
                    OpenSetupExe(ieSetuppath + "\\" + x64);
                }
                else {
                    string x86 = "IE9-Windows7-x32-chs.exe";
                    OpenSetupExe(ieSetuppath + "\\" + x86);
                }
            }

            if (st.path.Equals(string.Empty))
            {
                WChat.path.paths = st.path = System.Environment.CurrentDirectory + "\\temp";
                if (!Directory.Exists(st.path))
                    Directory.CreateDirectory(st.path);
                st.Save();
            }
            else {
                path.paths = st.path;

                if (path.paths!= string.Empty) {
                    string sqllite_path = System.Environment.CurrentDirectory + "\\hq_chatlog.db";  //文件路径
                    string sqllite_usage_path = path.paths + "\\hq_chatlog.db";   //工作时的路径
                    if (!File.Exists(sqllite_usage_path)) {
                        if (File.Exists(sqllite_path)) {
                            File.Copy(sqllite_path, sqllite_usage_path);  //复制sqllite数据库到工作目录
                        }else {
                            MessageBox.Show("文件丢失，请重新安装软件");
                        }
                    }
                }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
            st.robotOpen = false;
            st.AotuOpen = false;
            st.Save();

            //DAL.LoginStatusService ls = new DAL.LoginStatusService();
            //ls.SetStatusLand(ls.SearchAdministration(st.UseAcct), st.UseAcct, 0);    //设置退出状态
            //ls.SetLoginChild(st.UseAcct, string.Empty, 0);
            show_msg.Visible = false;
            show_msg.Dispose();
            Application.Exit();
        }
        /// <summary>
        /// 获取选中的项目的名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wxTabContral1_SelectedIndexChanged(object sender, EventArgs e) {
            if (wxTabContral1.SelectedTab!=null) {
                string item = wxTabContral1.SelectedTab.Name.ToString();
            }
        }

        private void 退出软件ToolStripMenuItem_Click( object sender, EventArgs e ) {
            st.robotOpen = false;
            st.Save();
            show_msg.Visible = false;
            Application.Exit();
        }

        private void 关于环球云ToolStripMenuItem_Click( object sender, EventArgs e ) {
            string helpurl = "http://www.pipacaijing.com/";
            hqbrower hb = new hqbrower();
            hb.openwebpage(helpurl);
            hb.Show();
        }

        private void 设置ToolStripMenuItem_Click( object sender, EventArgs e ) {
            SttingForm sf = new SttingForm();
            sf.Show();
        }

        private void show_msg_Click( object sender, EventArgs e ) {
            if (this.WindowState == FormWindowState.Minimized) {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
                this.Activate();
            }
        }

        private void wxTabContral1_tabClose( object sender, MouseEventArgs e ) {
            if (wxTabContral1.SelectedTab!=null) {
                string item = wxTabContral1.SelectedTab.Name.ToString();
                try {
                    if (login_wxb[item] != null) {
                        login_wxb[item].jump = true;
                        login_wxb.Remove(item);   //将该值移除
                    }
                }
                catch (Exception es) {
                    WriteLog.Writelog("wxTabContral1_tabClose", es.ToString());
                }
            }
        }

        private void Form1_FormClosing( object sender, FormClosingEventArgs e ) {
        }

        private void btn_group_Click( object sender, EventArgs e ) {
            GroupAssistant ga = new GroupAssistant();
            ga.meUser_list = pro_me;
            ga.Show();
        }

        private void pictureBox1_Click( object sender, EventArgs e ) {
            WXService wxs = new WXService();
            wxs.Test("http://localhost:52236/daliang/products");
        }
    }
}

